package com.lgf.extdemo.service;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.lgf.extdemo.pojo.Demo;
import com.lgf.extdemo.pojo.Tree;

public class TreeService {
	/**
	 * 把demo的值存放到Tree中去
	 * @return
	 */
	public String putIntoTree(List<Demo> demoList, int id, int depth) {
		Tree tempTree;
		List<Tree> list = new ArrayList<Tree>();
		for (Demo demo : demoList) {
			tempTree = new Tree();
			tempTree.setId(demo.getId());
			tempTree.setPid(demo.getPid());
			tempTree.setText(demo.getText());
			tempTree.setLeaf(isleaf(demo.getId(),demoList));
			tempTree.setShowLeaf(true);
			tempTree.setHref(demo.getUrl());
			tempTree.setIconCls(demo.getIconCls());
			list.add(tempTree);
		}
		return parseToJson(list,id,depth);
	}

	/**
	 * 转换成JsonObject
	 */
	private String parseToJson(List<Tree> list, int id, int depth) {
		JSONObject jsonObj=new JSONObject();
		JSONArray childList=new JSONArray();
		if(list.size() > 0){
			childList = getChild(list,id,depth);
		}
		//return jsonObj.put("children", childList);
		return childList.toString();
	}

	/**
	 * 获得子节点
	 */
	private JSONArray getChild(List<Tree> list, int id, int depth) {
		JSONArray childList=new JSONArray();
		for (Tree tree : list) {
			if (tree.getPid() == id) {
				JSONObject obj = new JSONObject();
				tree.parseToJson(obj);
				if (depth > 0 && !tree.isLeaf()) {
					obj.put("children", getChild(list,tree.getId(),depth-1));
				}
				childList.put(obj);
			}
		}
		return childList;
	}

	/**
	 * 判断是否是叶子节点
	 */
	private boolean isleaf(int id, List<Demo> demoList) {
		for (Demo demo : demoList) {
			if (demo.getPid() == id) {
				return false;
			}
		}
		return true;
	}
}
